(function($) {
	//--------------------
	// 绑定YM.data数据处理
	$.fn.bindYMData = function(type, params) {
		if (this.size()==0 || !YM) return this;
		if (YM.data && YM.data[type]) {
			YM.data[type](this, params);
		}
		return this;
	};
	$.fn.validFormElement = function(params) {
		this.data('validParam', params);
		switch(this.tagName()) {
			case 'input':
				this.blur(function() {
					var element = $(this);
					var params = $(this).data('validParam');
					var val = element.val().trim();
					var emptyChar = params.emptyChar || '';
					if (params.validEmpty && (val==emptyChar || val=='')) {
						element.bindYMData('ShowErrorString', params.emptyError);
						element.data('error', true);
					} else if (val==emptyChar || val=='') {
						element.bindYMData('ShowErrorString');
						element.data('error', false);
					} else if (params.validMethod && !YM.valid[('is-'+params.validMethod).toCamelCase()](val, params.methodParam)) {
						element.bindYMData('ShowErrorString', params.methodError);
						element.data('error', true);
					} else if (params.validRegex && !params.validRegex.test(val)) {
						element.bindYMData('ShowErrorString', params.regexError);
						element.data('error', true);
					} else if (params.validCompare && val!=params.validCompare.val().trim()) {
						element.bindYMData('ShowErrorString', params.compareError);
						element.data('error', true);
					} else {
						element.bindYMData('ShowErrorString');
						element.data('error', false);
					}
					element.data('valid', true);
				});
				break;
			case 'select':
				this.change(function() {
					$(this).validSelection();
				});
				break;
		}
	};
	$.fn.validSelection = function() {
		var element = this;
		var params = this.data('validParam');
		var val = element.val().trim();
		var emptyChar = params.emptyChar || '';
		if (params.validEmpty && val==emptyChar) {
			element.bindYMData('ShowErrorString', params.emptyError);
			element.data('error', true);
		} else if (params.validItems && params.validItems.indexOf(val)>=0) {
			element.bindYMData('ShowErrorString', params.itemsError);
			element.data('error', true);
		} else {
			element.bindYMData('ShowErrorString');
			element.data('error', false);
		}
		element.data('valid', true);
	};	
	$.bankCardFormat = function(card, len){
		var ca = [];
		for (var i=0; i<card.length; i=i+len) {
			ca.push(card.substr(i,len)+' ');
		}
		return (card.length==16)?ca.join('').trim():ca.join('');
	};
	$.fn.autoSplitLetters = function() {
		this.attr('maxlength', 22);
		this.css('ime-mode', 'disabled');
		this.bind('keypress', function(e) {
			try {
				if (e.shiftKey) return false;
				var code=e.which||e.keyCode||0;
				return code==8||code==32||(e.which==0&&e.keyCode==37)||(e.which==0&&e.keyCode==39)||(code>=48&&code<=57)||(e.which==0&&e.keyCode==46);
			} catch(err) {}
		});
		this.bind('keyup', function(e) {
			var val = this.value;
			if (val.length == 22) return;
			val = val.replace(/[\s-]/g, '');
			if (val.length>0 && val.length%4==0) {
				this.value = $.bankCardFormat(val, 4);
			}
		});
	};
	//--------------------
	// 使用方式：
	// YM.ajax('post', url, param, onSuccess, onError);
	// YM.ajax(url, param, onSuccess, onError);
	// YM.ajax('post', url, onSuccess, onError);
	// YM.ajax(url, onSuccess, onError);
	YM.ajax = function(type, url, param, onSuccess, onError) {
		if (type!='get' && type!='post') {
			onError = onSuccess;
			onSuccess = param;
			param = url;
			url = type;
			type = 'get';			
		}
		if ($.isFunction(param)) {
			onError = onSuccess;
			onSuccess = param;
			param = {};
		}
        var _url = url.getPathName();
        var _param = url.getQueryJson() || {};
		_param.async = true;
		_param._ = (new Date()).getTime();
		$.extend(_param, param||{});
		$.ajax({ type:type, url:_url, data:_param, success:onSuccess, error:onError });
	};
	// 使用方式：
	// YM.getJSON(url, onSuccess);
	// YM.getJSON(url, param, onSuccess);
	YM.getJSON = function(url, param, onSuccess) {
		if ($.isFunction(param)) {
			onSuccess = param;
			param = {};
		}
		param = param || {};
		param.async = true;
		param._ = (new Date()).getTime();
		$.getJSON(url, param, onSuccess);
	};
	YM.page.dialog.setContent = function(html) {
		YM.load('util.dialog', function() {
			YM.util.dialog.setContent(html);
			YM.util.dialog.setAutoHeight();
		});
	};
	//--------------------
	YM.valid.isLogName = function(str) {
		return (YM.valid.isEmail(str) || YM.valid.isMobile(str));
	};
	YM.valid.isRealName = function(str) {
		return /^[A-Za-z \u4E00-\u9FA5]+$/.test(str);
	};
	YM.valid.isLogPass = function(str) {
		return (str.length>=6 && str.length<=16 && YM.valid.isAlphanumeric(str));
	};
	YM.valid.isTradePass = function(str) {
		return (str.length>=8 && str.length<=20 && YM.valid.isAlphanumeric(str));
	};		// 卡号校验 模10检查
	YM.valid.isCardNo = function(str, cardType) {
		var cards = {
			"Visa": { lengths: "13,16", prefixes: "4", checkdigit: true },
			"MasterCard": { lengths: "16", prefixes: "51,52,53,54,55", checkdigit: true },
			"BankCard": { lengths: "16,19", prefixes: "4,5,6", checkdigit: true }
		};
		if (!cards[cardType]) return false;
		var cardNo = str.replace(/[\s-]/g, ""); // remove spaces and dashes
		var cardexp = /^[0-9]{13,19}$/;
		if (cardNo.length==0 || !cardexp.exec(cardNo)) {
			return false;
		} else {
			cardNo = cardNo.replace(/\D/g, ""); // strip down to digits
			var modTenValid = true;
			var prefixValid = false;
			var lengthValid = false;
			// 模10检查
			if (cards[cardType].checkdigit) {
				var checksum = 0, mychar = "", j = 1, calc;
				for (i = cardNo.length - 1; i >= 0; i--) {
					calc = Number(cardNo.charAt(i)) * j;
					if (calc > 9) {
						checksum = checksum + 1;
						calc = calc - 10;
					}
					checksum = checksum + calc;
					if (j == 1) { j = 2 } else { j = 1 };
				}			
				if (checksum % 10 != 0) modTenValid = false;
			}
			if (cards[cardType].prefixes=='') {
				prefixValid = true;
			} else {
				// 前缀字符检查
				var prefix = cards[cardType].prefixes.split(",");				
				for (i=0; i<prefix.length; i++) {
					var exp = new RegExp("^" + prefix[i]);
					if (exp.test(cardNo)) prefixValid = true;
				}
			}
			// 卡号长度检查
			var lengths = cards[cardType].lengths.split(",");
			for (j=0; j<lengths.length; j++) {
				if (cardNo.length == lengths[j]) lengthValid = true;
			}
			if (!modTenValid || !prefixValid || !lengthValid) {
				return false;
			} else {
				return true;
			}
		}
	};
	//--------------------
	YM.namespace('YM.data');
	//--------------------
	// 使用前提：ajax加载的html中，没有跳出链接
	YM.data.HtmlLoad = function(elm, url) {
		var url = url || elm.attr('data-url');
		YM.data.loadHTML(elm, url, function(elm) {
			elm.find('a').click(function() {
				var _url = $(this).attr('href') || '#';
				var _target = $(this).attr('target') || '';
				if (url!='#' && _target=='') {
					elm.bindYMData('HtmlLoad', $(this).attr('href'));
				}
				return false;
			});
		});
	};
	// 使用方式
	// YM.data.loadHTML(elm, url, callback);
	// YM.data.loadHTML(elm, url, data, callback);
	YM.data.loadHTML = function(elm, url, data, callback) {
		if ($.isFunction(data)) {
			callback = data;
			data = null;
		}
		YM.ajax(url, data, function(req) {
			elm.html(req);
			if (callback) callback(elm);
		}, function() {
            elm.html('内容加载失败！');
		});
	};
	YM.data.getElementType = function(elm) {
		var tag = elm.tagName();
		return (tag=='input') ? (elm.attr('type')||'text') : tag;
	};
	// 返回element的值
	YM.data.getElementValue = function(elm) {
		if (elm.size() == 0) return '';
		var type = YM.data.getElementType(elm);
		switch (type) {
			case 'checkbox':
			case 'radio':
				return YM.data.getCheckedValue(elm).join(',');
			default:
				return elm.val();
		}
	};
	// 获取多项内容的值
	YM.data.getElementsValue = function(elm, option) {
		var option = option || {};
		var arr = [];
		elm.each(function() {
			if ($(this).val()!='' || !option.noEmpty) {
				arr.push((option.quote) ? ('\"' + $(this).val() + '\"') : $(this).val());
			}
		});
		return arr;
	};
	// 获取多项内容的文本
	YM.data.getElementsText = function(elm, noEmpty) {
		var arr = [];
		elm.each(function() {
			if ($(this).text()!='' || !noEmpty) arr.push($(this).text());
		});
		return arr;
	};
	// 获取选择数量
	YM.data.getCheckedSize = function(elm) {
		var checkedSize = 0;
		elm.each(function() { if (this.checked) checkedSize++; });
		return checkedSize;
	};
	// 获取选择的值
	YM.data.getCheckedValue = function(elm, quote) {
		var arr = [];
		elm.each(function() {
			if (this.checked) arr.push((quote) ? ('\"' + this.value + '\"') : this.value);
		});
		return arr;
    };
	//--------------------
	// 数据校验
	YM.data.checkElementsInvalid = function(element) {
		var elements = $(element);
		if (elements.size()>0) {
			for (var j=0; j<elements.size(); j++) {
				var elm = elements.eq(j);
				if (!elm.data('valid')) elm[elm.tagName()=='select'?'validSelection':'blur']();
				if (elm.data('error')) {
					if (elm.tagName()=='input') elm.focus();
					return true;
				}
			}
		}
		return false;
	};
	YM.data.checkElementIsEmpty = function(element, errorText, isParent) {
		var elm = $(element);
		if (elm.size()==0) return false;
		if (elm.val().trim()=='') {
			if (isParent) {
				elm.parent().bindYMData('ShowErrorString', errorText);
			} else {
				elm.bindYMData('ShowErrorString', errorText);
			}
			if (elm.tagName()=='input') elm.focus();
			return true;
		}
		return false;
	};
	YM.data.ShowErrorString = function(elm, str) {
		elm.each(function() {
			var errElm = $(this).siblings('span.error');
			if (errElm.size()==0) {
				errElm = $('<span class="error"></span>');
				$(this).after(errElm);
			}
			errElm.html(str||'');
			if (str) {
				errElm.css('display','inline');
				$(this).data('error', true);
			} else {
				errElm.hide();
				$(this).data('error', false);
			}		
		});
	};
	//--------------------
	YM.namespace('YM.ui');
	YM.ui.ListTableDataColResize = function(elm) {
		var tableframe = elm;
		var table = elm.find('table');
		if (table.attr('width')=='100%') return;
		// 计算表格宽度
		var tablewidth = 0;
		table.find('colgroup col').each(function() {
			if (!$(this).attr('width')) $(this).attr('width', '100');
			tablewidth += parseInt($(this).attr('width'),10);
		});
		table.css('width', tablewidth+'px');
		// 表格宽度自适应处理
		var autowidth = false;
		if (table.width() <= tableframe.width()) {
			table.css('width', tableframe.width()+1);
			if (table.find('colgroup col:last').size()>0) {
				table.find('colgroup col:last')[0].setAttribute('width', 'auto');
			}
			autowidth = true;
		} else if ($.browser.msie && parseInt($.browser.version)==9) {
			tableframe.css('overflow-x', 'scroll');
		}
	};
	YM.ui.ListTableRowStyleUpdate = function(elm) {
		elm.find('tbody tr').each(function(i) {
			if (i%2) $(this).addClass('row2');
			if ($.browser.isIE6) $(this).bindYMUI('ElementHover', {hoverClass:'hover'});
		});
		elm.find('col:first').addClass('first');
	};
	//--------------------
	YM.namespace('YM.page.secondhand');
	// 页面初始化
	YM.page.secondhand.init = function() {
		this.scrollTopBoard();
		this.initSideMenu();
		this.initListTable();
		this.initPageEvent();
	};
	// 顶部动态播放
	YM.page.secondhand.scrollTopBoard = function() {
		if ($('.topboard .newslist').size()==0) return;
		setInterval(function() {
			var firstItem = $('.topboard .newslist li:eq(0)');
			firstItem.animate({marginLeft:0-firstItem.width()}, 2000, function() {
				firstItem.css('margin-left', '0');
				firstItem.parent().append(firstItem);
			});
		}, 5000);
	};
	// 左侧菜单折叠/展开
	YM.page.secondhand.initSideMenu = function() {
		$('.sidemenu ul>li>span').click(function() {
			if ($(this).parent().hasClass('on')) {
				$(this).parent().removeClass('on');
			} else {
				$(this).parent().addClass('on');
			//	$(this).parent().siblings('.on').removeClass('on');
			}
		});
	};
	// 初始化表格处理
	YM.page.secondhand.initListTable = function() {
		$('.list-table').bindYMUI('ListTableDataColResize');
		$('.list-table').bindYMUI('ListTableRowStyleUpdate');
	};
	// 初始化页面事件处理
	YM.page.secondhand.initPageEvent = function() {
		$('input.e-checkall').bindYMUI('CheckAll');
		$('input.txt-datepicker').bindYMUI('DatePicker');
		$('.custom-label').bindYMUI('ElementHover', {hoverClass:'custom-label-hover'});
		$('.e-htmlload').bindYMData('HtmlLoad');
		$('.e-popwin').bindYMUI('PopDialogWin', { width:500, height:200 });
	};
	$(document).ready(function() {
		YM.page.secondhand.init();
	});
})(jQuery);